package com.ruoyi.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysConfigService configService;

//    @Autowired
//    private RedisTemplate redisTemplate;

    @Autowired
    private ISysUserService userService;
    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
    /**
     * 发送手机验证码
     */
    @PostMapping("/login/captchaPhone")
    public AjaxResult sendPhoneCaptcha(@RequestParam(required = false) String phoneNumber) {

        // 打印请求对象，查看是否接收到参数
        System.out.println("请求对象信息：" + RequestContextHolder.getRequestAttributes());
        System.out.println("接收到的 phoneNumber：" + phoneNumber);
        phoneNumber = phoneNumber.trim();  // 清除前后的空格、换行符等

//        System.out.println("phoneNumber 是否为空: " + StringUtils.isEmpty(phoneNumber));
//        System.out.println("phoneNumber 类型: " + phoneNumber.getClass().getName());
//        System.out.println("phoneNumber 值: " + phoneNumber);
//        System.out.println("phoneNumber 正则匹配结果 (String): " + phoneNumber.matches("^\\d{11}$"));
//        System.out.println("phoneNumber 正则匹配结果 (StringUtils): " + StringUtils.isMatch(phoneNumber, "^\\d{11}$"));

        if (StringUtils.isEmpty(phoneNumber)) {
            return AjaxResult.error("手机号不能为空，请提供有效的手机号码");
        }

        // 格式校验（11位数字）
        if (!phoneNumber.matches("^\\d{11}$")) {
            return AjaxResult.error("手机号格式不正确");
        }

        // 查询用户是否存在
        SysUser user = userService.selectUserByPhonenumber(phoneNumber);
        if (user == null) {
            return AjaxResult.error("手机号未注册，请先注册");
        }

        // 生成6位验证码
        String captcha = String.format("%06d", new Random().nextInt(999999));
        String uuid = IdUtils.simpleUUID();
        String redisKey = "login:captcha:" + uuid;

        // 存入 Redis，并设置过期时间5分钟
//        redisTemplate.opsForValue().set(redisKey, captcha, 5, TimeUnit.MINUTES);
        redisCache.setCacheObject(redisKey, captcha, 5, TimeUnit.MINUTES);


        // 模拟发送验证码
        System.out.println("发送验证码到 " + phoneNumber + ": " + captcha);

        HttpHeaders headers = new HttpHeaders();
        headers.add("x-captcha-uuid", uuid);

        // 返回验证码和 uuid（前端需携带 uuid 进行登录验证）
        return AjaxResult.success()
                .put("uuid", uuid)
                .put("captcha", captcha)
                .put("phoneNumber", phoneNumber);
    }

    /**
     * 发送手机注册验证码接口
     */
    @PostMapping("/register/captchaPhone")
    public AjaxResult sendRegisterPhoneCaptcha(@RequestParam String phoneNumber) {
        // 校验手机号是否为空
        if (StringUtils.isEmpty(phoneNumber)) {
            return AjaxResult.error("手机号不能为空");
        }

        // 校验手机号格式（11位数字）
        if (!phoneNumber.matches("^\\d{11}$")) {
            return AjaxResult.error("手机号格式不正确");
        }

        // 查询用户是否存在（可选，根据业务判断是否允许未注册用户获取验证码）

        // 生成6位验证码
        String captcha = String.format("%06d", new Random().nextInt(999999));
        String uuid = IdUtils.simpleUUID();
//        String redisKey = CacheConstants.PHONE_CAPTCHA_KEY + uuid;
        String redisKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;


        // 存入 Redis 并设置过期时间 5 分钟
        redisCache.setCacheObject(redisKey, captcha, 5, TimeUnit.MINUTES);

        // 模拟发送验证码（后续替换为真实短信服务）
        System.out.println("发送验证码到 " + phoneNumber + ": " + captcha);

        // 返回结果
        return AjaxResult.success()
                .put("uuid", uuid)
                .put("captcha", captcha)
                .put("phoneNumber", phoneNumber);
    }

}
